﻿using SkyApm.Config;
using SkyApm.Tracing;
using System.Collections.Generic;

namespace WebApmDemo1.Models
{
    /// <summary>
    /// 自定义忽略规则
    /// </summary>
    public class IgnorePathInterceptor : ISamplingInterceptor
    {
        private readonly bool _sample_on;
        private readonly List<string> _ignorePaths;

        public int Priority => int.MinValue + 998;

        public IgnorePathInterceptor(IConfigAccessor configAccessor)
        {
            var ignorePaths = configAccessor.Get<SamplingConfig>().IgnorePaths;
            _sample_on = ignorePaths?.Count > 0;
            if (_sample_on)
            {
                _ignorePaths = ignorePaths;
            }
        }

        public bool Invoke(SamplingContext samplingContext, Sampler next)
        {
            if (!_sample_on)
                return next(samplingContext);
            foreach (var pattern in _ignorePaths)
            {
                if (pattern.StartsWith("*") && samplingContext.OperationName.Contains(pattern.Substring(1)))
                    return false;
            }
            return next(samplingContext);
        }
    }
}
